package nc.ui.arap.badacc;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import nc.ui.pub.bill.BillListPanel;
import nc.vo.arap.badacc.DstlCaseDetailVO;
import nc.vo.arap.badacc.DstlCaseTimeItem;
import nc.vo.pub.BusinessException;

public class OnDelLineButtonHandler extends ButtonOnClickHandler {

	private DstlCaseMainPanel mainPanel;

	public OnDelLineButtonHandler(DstlCaseMainPanel mainPanel) {
		this.mainPanel = mainPanel;
	}

	public DstlCaseMainPanel getMainPanel() {
		return mainPanel;
	}

	@Override
	protected void handleEvent() throws BusinessException {
		if (getMainPanel().isCard()) {
			int[] rows = getSelectedRows(new BillListPanel[] {getMainPanel().getBillCardUIPanel().getBillListPanel()});
			for (DstlCaseDetailVO detail : getSelectedDetailVOS()) {
				getMainPanel().getDeletedDetails().add(detail);
			}
			if (rows == null || rows.length <= 0) {
				rows = new int[1];
				rows[0] = getMainPanel().getBillCardUIPanel().getBillListPanel().getHeadTable().getRowCount() - 1;
				if (rows[0] < 0) return;
			}
			
			if (getMainPanel().getBillCardUIPanel().isTimeControl()) {
				for (int row : rows) {
					getMainPanel().getBillCardUIPanel().getDstlCaseTimeItemMap().remove(getMainPanel().getBillCardUIPanel().genRightRow(row));
				}
				Map<Integer, DstlCaseTimeItem[]> newTimeMap = new HashMap<Integer, DstlCaseTimeItem[]>();
				
				int i = 0;
				List<Integer> leftRows = new ArrayList<Integer>();
				leftRows.addAll(getMainPanel().getBillCardUIPanel().getDstlCaseTimeItemMap().keySet());
				Collections.sort(leftRows);
				for (int row : leftRows) {
					newTimeMap.put(i ++, getMainPanel().getBillCardUIPanel().getDstlCaseTimeItemMap().get(row));
				}
				getMainPanel().getBillCardUIPanel().setDstlCaseTimeItemMap(newTimeMap);
				
			}
			getMainPanel().getBillCardUIPanel().delLine(rows);
			
		}

	}
	
	private DstlCaseDetailVO[] getSelectedDetailVOS() {
		int[] rows = getSelectedRows(new BillListPanel[] {getMainPanel().getBillCardUIPanel().getBillListPanel()});
		DstlCaseDetailVO[] selectedDetails = new DstlCaseDetailVO[rows.length];
		{
			int i = 0;
			for (int row : rows) {
				selectedDetails[i ++] = (DstlCaseDetailVO) getMainPanel().getBillCardUIPanel().getBillListPanel()
				.getHeadBillModel().getBodyValueRowVO(row, 
						DstlCaseDetailVO.class.getName());
			}
		}
		return selectedDetails;
	}

	@Override
	protected void updateBtns() {
		// TODO Auto-generated method stub

	}

}
